﻿using System;
using System.Web.DynamicData;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace PD.Web.DynamicData.EntityTemplates
{
    /// <summary>
    /// Defines the class for default display entity template.
    /// </summary>
    public partial class DefaultEntityTemplate : System.Web.DynamicData.EntityTemplateUserControl
    {
        /// <summary>
        /// Represents a database column that is used by Dynamic Data.
        /// </summary>
        private MetaColumn currentColumn;

        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load"/> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs"/> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            foreach (MetaColumn column in Table.GetScaffoldColumns(this.Mode, this.ContainerType))
            {
                this.currentColumn = column;
                Control item = new _NamingContainer();
                this.EntityTemplate1.ItemTemplate.InstantiateIn(item);
                this.EntityTemplate1.Controls.Add(item);
            }
        }

        /// <summary>
        /// Handles the Init event of the Label control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Label_Init(object sender, EventArgs e)
        {
            Label label = (Label)sender;
            label.Text = this.currentColumn.DisplayName;
        }

        /// <summary>
        /// Handles the Init event of the DynamicControl control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void DynamicControl_Init(object sender, EventArgs e)
        {
            DynamicControl dynamicControl = (DynamicControl)sender;
            dynamicControl.DataField = this.currentColumn.Name;
        }

        /// <summary>
        /// A container control that creates a new ID namespace.
        /// </summary>
        public class _NamingContainer : Control, INamingContainer
        {
        }
    }
}
